# -*- coding: utf-8 -*-
# @Project : 4、TCP协议相关自动化
# @File    : HandleString.py
# @Author  : 朱宽
# @Time    : 2021/4/21 18:09
# @Software: Win10 / Python3 / Pycharm

class HandleString():
    '''
    操作字符串
    '''

    def joint_string(self, data):
        '''
        拼接字符串
        :param data: ['11','22']-->'1122'，按协议顺序排好的列表
        :return: '1122'
        '''
        res = ''.join(data)
        return res

    def first_add(self, per, add_string):
        '''
        给字符串添加指定首部内容
        :param per: 字符串本身
        :param add_string: 指定首部
        :return:
        '''
        result_string = add_string + per

        return result_string

    def list_hex_string(self,hex_string):
        '''
        将16进制字符串转换为列表
        :param hex_string:
        :return:
        '''
        y = bytearray.fromhex(hex_string)  # var1 = bytearray.fromhex("01020304")  #将hexstring 转化为 字节数组。
        result = list(y)  # 将字节数组列表化

        return result

    def hex_str_to_byte(self, hex_str, type='bytearray'):
        '''
        将16进制数的字符串转换为字节码
        :param hex_str: '78781101075253367890024270003201000512790D0A'
        :param type: 默认 bytearray ，也可以是 bytes
        :return:
        '''
        try:
            if type == 'bytearray':
                res = bytearray.fromhex(hex_str)
                return res
            elif type == 'bytes':
                res = bytes.fromhex(hex_str)
                return res
        except Exception as e:
            return e

    def bytes_to_hex_str(self, res_bytes):
        '''
        将字节码转换为 16进制数，并以字符串的形式显示
        :param bytes: 类型为：<class 'bytes'>；内容为： b'xx\x05\x01\x00\x05\x9f\xf8\r\n'
        :return:字节码转16进制数的字符串： 7878050100059ff80d0a
        '''
        res = res_bytes.hex()
        return res

    def remove_space(self,hex_string):
        '''
        去除字符串空格，返回不带空格的字符串
        :return:
        '''
        res=hex_string.split(" ")
        r=''
        for i in range(0,len(res)):
            r=r+res[i]

        return r


if __name__ == '__main__':
    data = ['1', 'a', '2', 'b', '34', 'ef', '567890235rd77']
    test = HandleString()
    result = test.joint_string(data)
    print(result, '\t', type(result))


    str1='0100002d013571060003000100440300363031313100000000000000000000000000000042443232300171107271061601D4C1423030304031'
    result1=test.list_hex_string(hex_string=str1)
    print(result1)
